package de.jmda.home.ui.vaadin;

import javax.ejb.EJB;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.apache.log4j.Logger;
import org.vaadin.virkki.cdiutils.application.UIContext.UIScoped;

import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;

import de.jmda.cbo.user.User;
import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext;
import de.jmda.home.bl.usermgmt.UserManagementBean;

/**
 * Main UI class
 */
@SuppressWarnings("serial")
@UIScoped // virkii version
//@CDIUI // vaadin version, not yet available
//@Root  // vaadin version, not yet available
public class MainUI extends UI
{
	private final static Logger LOGGER = Logger.getLogger(MainUI.class);

	@EJB
	private UserManagementBean userManagement;

	@Override
	protected void init(VaadinRequest request)
	{
		// default session context will put itself into the session context during
		// construction, no handle has to be stored here, session context data will
		// be available session wide through static access method
		new DefaultSessionContext();

		DefaultSessionContext.get().setUserManagement(userManagement);
		initAdminUser();
		initUI();
	}

	private void initAdminUser()
  {
		LOGGER.debug(userManagement.allUsersAsString("users before initialisation"));

		User user = userManagement.findUserByUsername(UserManagementBean.ADMIN);
		
		if (user == null)
		{
			try
      {
	      userManagement.createAdminRegistrationRequest();
      }
      catch (AddressException e)
      {
      	LOGGER.error("failure sending mail for admin registration", e);
      }
      catch (MessagingException e)
      {
      	LOGGER.error("failure sending mail for admin registration", e);
      }
		}
		
		LOGGER.debug(userManagement.allUsersAsString("users after initialisation"));
  }

	private void initUI()
	{
		setWidth(1200, Unit.PIXELS);
		setHeight(100, Unit.PERCENTAGE);

		MainUIComponent content = new MainUIComponent();
		content.setSizeFull();

		setContent(content);
	}
}